package com.mindskip.xzs.service.impl;

import com.mindskip.xzs.domain.entity.TextContent;
import com.mindskip.xzs.repository.BaseMapper;
import com.mindskip.xzs.repository.TextContentMapper;
import com.mindskip.xzs.service.TextContentService;
import com.mindskip.xzs.utility.JsonUtil;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TextContentServiceImpl extends BaseServiceImpl<TextContent> implements TextContentService {

    private final TextContentMapper textContentMapper;

    public TextContentServiceImpl(BaseMapper<TextContent> baseMapper, TextContentMapper textContentMapper) {
        super(baseMapper);
        this.textContentMapper = textContentMapper;
    }

    /**
     * 创建一个TextContent，将内容转化为json，回写到content中，不入库
     */
    @Override
    public <T, R> TextContent jsonConvertInsert(List<T> list, Date now, Function<? super T, ? extends R> mapper) {
        String frameTextContent;
        if (null == mapper) {
            frameTextContent = JsonUtil.toJsonStr(list);
        } else {
            List<R> mapList = list.stream().map(mapper).collect(Collectors.toList());
            frameTextContent = JsonUtil.toJsonStr(mapList);
        }
        return new TextContent(frameTextContent, now);
    }

    /**
     * 修改一个TextContent，将内容转化为json，回写到content中，不入库
     */
    @Override
    public <T, R> TextContent jsonConvertUpdate(TextContent textContent, List<T> list, Function<? super T, ? extends R> mapper) {
        String frameTextContent;
        if (null == mapper) {
            frameTextContent = JsonUtil.toJsonStr(list);
        } else {
            List<R> mapList = list.stream()
                    .map(mapper)
                    .collect(Collectors.toList());
            frameTextContent = JsonUtil.toJsonStr(mapList);
        }
        textContent.setContent(frameTextContent);
        return textContent;
    }

    @Override
    public List<TextContent> getTextContentBatch(List<Integer> ids) {
        return textContentMapper.selectByIds(ids);
    }


}
